package com.javaframe.role.web;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.beanutils.BeanUtils;

import com.javaframe.role.entity.User;
import com.javaframe.role.service.UserService;
import com.javaframe.role.tools.ConditionInfo;
import com.javaframe.role.tools.GenericsUtils;
import com.javaframe.role.tools.PageInfo;




@Controller
public class UserController {

	UserService service;
	
	@Autowired
	public void setUserService(UserService userService) {
		this.service = userService;
	}

	@RequestMapping(method=RequestMethod.POST, value="/users")
	@ResponseBody
	public Map<String, Object> getUsers(@RequestBody ModelMap map){
		List<ConditionInfo> listCondition = GenericsUtils.formatMultiFilter(map);
		PageInfo page=GenericsUtils.formatPageInfo(map);
		List<User> users=service.findAll(listCondition,page);
		return GenericsUtils.formatResponseData(map,users,page,"userId");
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/create")
	@ResponseBody
	public void addUser(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		for(int i=0;i<100;i++){
		User user = new User();
		user.setDeleted(Short.valueOf("0"));
		user.setCreateTime(new Timestamp(System.currentTimeMillis()));
		BeanUtils.copyProperties(user, map);
		service.save(user);
		}
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/fetch/{id}")
	@ResponseBody
	public User getUser(@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
        return service.findById(id);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/update/{id}")
	@ResponseBody
	public void updateUser(@RequestBody Map<String, Object> map,@PathVariable Integer id) throws IllegalAccessException, InvocationTargetException{ 
		User user=new User();
		BeanUtils.copyProperties(user, map);
		service.save(user);
    }
	
	@RequestMapping(method=RequestMethod.POST, value="/user/delete")
	@ResponseBody
	public void deleteUser(@RequestBody Map<String, Object> map) throws IllegalAccessException, InvocationTargetException{ 
		map.put("table", "User");
		map.put("identifier", "userId");
		service.delete(map);
    }
}
